# -*- coding: utf-8 -*-

"""
@Remark: 用户地址管理
"""
import re
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from apps.project.models import *
from utils.jsonResponse import SuccessResponse,ErrorResponse
from rest_framework_simplejwt.authentication import JWTAuthentication
from utils.common import get_parameter_dic,REGEX_MOBILE
from django.core.cache import cache
from utils.locationanalysis import gettecentlnglat
from utils.serializers import CustomModelSerializer
from utils.viewset import CustomModelViewSet
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from django.db.models import Q,F
from utils.imageupload import FileUpload
import django_filters
from django_filters.filters import *
from django_filters.rest_framework import DjangoFilterBackend
from django_filters import utils
from django_filters.filters import CharFilter

from utils.export_excel import export_sensor
import io
import xlwt
from django.http import HttpResponse
import json
import os
from django.conf import settings
import openpyxl

class ProjectSerializer(CustomModelSerializer):
    class Meta:
        model = Meida
        #fields = ["id"]
        exclude = ['description']
        read_only_fields = ["id"]

class ProjectCreateUpdateSerializer(CustomModelSerializer):
    class Meta:
        model = Meida
        fields = '__all__'

class PojectManagerFilter(django_filters.rest_framework.FilterSet):
    # 模糊搜索
    name = django_filters.CharFilter(field_name='name', lookup_expr='icontains')  # icontains表示该字段模糊搜索
    #开始时间
    beginAt = django_filters.DateTimeFilter(field_name='create_datetime', lookup_expr='gte')  # 指定过滤的字段
    #结束时间
    endAt = django_filters.DateTimeFilter(field_name='create_datetime', lookup_expr='lte')
    # 精确搜索
    status = django_filters.CharFilter(field_name='status')  # 自定义过滤
    class Meta:
        model = Meida
        fields = ['id', 'name', 'status', 'beginAt', 'endAt']

class ProjectViewSet(CustomModelViewSet):
    create_serializer_class = ProjectCreateUpdateSerializer
    update_serializer_class = ProjectCreateUpdateSerializer
    filterset_class = PojectManagerFilter
    queryset = Meida.objects.all().order_by('-create_datetime')
    serializer_class = ProjectSerializer
    #filterset_fields = ['status','name','id']
    #search_fields = ('name')
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]
    def upload(self, request, *args, **kwargs):
        result = FileUpload(request, "dwg")
        for excel_file in result['img']:
            wb = openpyxl.load_workbook(excel_file)
            sheet = wb.active
            for row in sheet.iter_rows(min_row=2):  # 假设第一行是标题行，从第二行开始
                sn = row[0].value
                house_name = row[2].value
                house_type = row[8].value
                house_face= row[8].value
                house_near= row[4].value
                house_size= row[5].value
                address= row[6].value
                house_build= row[7].value
                house_man= row[9].value
                house_price= row[10].value
                house_exits= row[11].value
                media_nums= row[13].value
                media_type= row[14].value
                media_disable= row[15].value
                # 创建或更新模型实例
                instance, created = Meida.objects.update_or_create(
                    sn=sn,
                    house_name=house_name,
                    house_type=house_type,
                    house_face=house_face,
                    house_near=house_near,
                    house_size=house_size,
                    address=address,
                    house_build=house_build,
                    house_man=house_man,
                    house_price=house_price,
                    house_exits=house_exits,
                    media_nums=media_nums,
                    media_type=media_type,
                    media_disable=media_disable
                )

        if result['code'] == 200:
            return SuccessResponse(data=result['img'], msg=result['msg'])
        else:
            return ErrorResponse(msg=result['msg'])
        

class CustomerSerializer(CustomModelSerializer):
    class Meta:
        model = Customer
        #fields = ["id"]
        exclude = ['description']
        read_only_fields = ["id"]

class CustomerCreateUpdateSerializer(CustomModelSerializer):
    class Meta:
        model = Customer
        fields = '__all__'

class CustomerManagerFilter(django_filters.rest_framework.FilterSet):
    # 模糊搜索
    name = django_filters.CharFilter(field_name='name', lookup_expr='icontains')  # icontains表示该字段模糊搜索
    #开始时间
    beginAt = django_filters.DateTimeFilter(field_name='create_datetime', lookup_expr='gte')  # 指定过滤的字段
    #结束时间
    endAt = django_filters.DateTimeFilter(field_name='create_datetime', lookup_expr='lte')
    # 精确搜索
    status = django_filters.CharFilter(field_name='status')  # 自定义过滤
    class Meta:
        model = Customer
        fields = ['id', 'name', 'status', 'beginAt', 'endAt']

class CustomerViewSet(CustomModelViewSet):
    create_serializer_class = CustomerCreateUpdateSerializer
    update_serializer_class = CustomerCreateUpdateSerializer
    filterset_class = CustomerManagerFilter
    queryset = Customer.objects.all().order_by('-create_datetime')
    serializer_class = CustomerSerializer
    #filterset_fields = ['status','name','id']
    #search_fields = ('name')
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]


class StoreSerializer(CustomModelSerializer):
    class Meta:
        model = Store
        #fields = ["id"]
        exclude = ['description']
        read_only_fields = ["id"]

class StoreCreateUpdateSerializer(CustomModelSerializer):
    class Meta:
        model = Store
        fields = '__all__'

class StoreManagerFilter(django_filters.rest_framework.FilterSet):
    # 模糊搜索
    name = django_filters.CharFilter(field_name='name', lookup_expr='icontains')  # icontains表示该字段模糊搜索
    #开始时间
    beginAt = django_filters.DateTimeFilter(field_name='create_datetime', lookup_expr='gte')  # 指定过滤的字段
    #结束时间
    endAt = django_filters.DateTimeFilter(field_name='create_datetime', lookup_expr='lte')
    # 精确搜索
    status = django_filters.CharFilter(field_name='status')  # 自定义过滤
    class Meta:
        model = Store
        fields = ['id', 'name', 'status', 'beginAt', 'endAt']

class StoreViewSet(CustomModelViewSet):
    create_serializer_class = StoreCreateUpdateSerializer
    update_serializer_class = StoreCreateUpdateSerializer
    filterset_class = StoreManagerFilter
    queryset = Store.objects.all().order_by('-create_datetime')
    serializer_class = StoreSerializer
    #filterset_fields = ['status','name','id']
    #search_fields = ('name')
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]